-module(ray).
-export([new/2, split/1, new/3]).
-export([get_weight/1, set_weight/2]).
-export([hittest/2]).

-record(ray, {origin, direction, weight=1}).

new(Origin, Direction, Weight) -> #ray{origin=Origin, direction=Direction, weight=Weight}.

new(Origin, Direction) ->#ray{origin=Origin, direction=Direction}.

split(#ray{origin=Origin, direction=Direction}) -> {Origin, Direction}.

get_weight(#ray{weight=Weight}) -> Weight.
set_weight(Ray=#ray{}, Weight) -> Ray#ray{weight=Weight}.

hittest(Ray, Scene) -> hittest(Ray, scene:get_objects(Scene), []).
hittest(_Ray, [], []) -> false;
hittest(_Ray, [], Hits) -> hd(lists:keysort(1, Hits));
hittest(Ray, [Object|Tail], Hits) ->
    case object:hittest(Ray, Object) of
        false -> hittest(Ray, Tail, Hits);
        HitFace -> hittest(Ray, Tail, [HitFace | Hits])
    end.
